#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
公众号：Test201728

日期: 2020/5/12 14:07

"""

import sys
import os
base_path = os.path.abspath(os.path.join(os.getcwd(), ".."))  # 获取上级目录
sys.path.append(base_path)
import HTMLTestRunner
from Util.http_email import send_email
from Base.base_request import request
from Util.codition_data import get_data
from Util.handle_cookie import write_cookie, get_cookie_value
from Util.handle_result import handle_result, handle_result_json, get_result_json
from Util.handle_header import get_header
from Util.handle_excel import excel_data
import json
import unittest
import ddt

data = excel_data.get_excel_data()


@ddt.ddt
class TestRunCaseDdt(unittest.TestCase):

    @ddt.data(*data)
    def test_main_case(self, data):
        cookie = None
        get_cookie = None
        header = None
        depend_data = None
        is_run = data[2]
        case_id = data[0]
        i = excel_data.get_rows_number(case_id)
        if is_run == 'yes':
            is_depend = data[3]  # 获取前置条件
            if data[7] == "form":
                data1 = json.loads(data[8])  # 读取用例中的数据字符串转成字典格式了
            if data[7] == "json":
                data1 = json.loads(data[8])
                data1 = json.dumps(data1)
            try:
                if is_depend:
                    depend_key = data[4]  # 获取依赖数据
                    depend_data = get_data(is_depend)
                    data1[depend_key] = depend_data
                    if data[10] == "yes":  # 通过Excel中的header值，控制是否需要把依赖数据的字典转出json格式
                        data1 = json.dumps(data1)  # 将依赖数据的字典转成json格式
                    if data[10] == "no":
                        pass
                method = data[6]
                url = data[5]
                is_header = data[10]
                excepect_method = data[11]
                excepect_result = data[12]
                cookie_method = data[9]
                if cookie_method == 'yes':
                    cookie = get_cookie_value('app')
                if cookie_method == 'write':
                    '''
                    必须是获取到cookie
                    '''
                    get_cookie = {"is_cookie": "app"}
                if is_header == 'yes':
                    header = get_header()

                res = request.run_main(
                    method, url, data1, cookie, get_cookie, header)
                # print(res)
                code = str(res['code'])
                message = res['msg']

                if excepect_method == 'mec':
                    config_message = handle_result(url, code)
                    try:
                        self.assertEqual(message, config_message)
                        excel_data.excel_write_data(i, 14, "通过")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                    except Exception as e:
                        excel_data.excel_write_data(i, 14, "失败")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                        raise e
                if excepect_method == 'code':
                    try:
                        self.assertEqual(excepect_result, code)
                        excel_data.excel_write_data(i, 14, "通过")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                    except Exception as e:
                        excel_data.excel_write_data(i, 14, "失败")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                        raise e
                if excepect_method == 'json':
                    if code == 200:
                        status_str = 'sucess'
                    else:
                        status_str = 'error'
                    excepect_result = get_result_json(url, status_str)
                    result = handle_result_json(res, excepect_result)
                    try:
                        self.assertTrue(result)
                        excel_data.excel_write_data(i, 14, "通过")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                    except Exception as e:
                        excel_data.excel_write_data(i, 14, "失败")
                        excel_data.excel_write_data(i, 15, json.dumps(res))
                        raise e
            except Exception as e:
                excel_data.excel_write_data(i, 14, "失败")
                raise e


if __name__ == "__main__":
    case_path = base_path + "/Run"
    report_path = base_path + "/Report/report.html"
    excel = base_path + "/Case/imooc.xlsx"
    discover = unittest.defaultTestLoader.discover(
        case_path, pattern="run_case_*.py")
    with open(report_path, "wb") as f:
        runner = HTMLTestRunner.HTMLTestRunner(
            stream=f, title="接口自动化报告", description="接口自动化测试报告")
        runner.run(discover)
    send_email(report_path)
